package ch10.shili;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

class NumberWorker implements Runnable{

    List<Integer> integers;

    int start;

    public NumberWorker(List<Integer> nums, int i) {
        integers = nums;
        start = i;
    }

    @Override
    public void run() {
        Thread t = Thread.currentThread();
        for (int i = start; i < start+100; i++){
            //System.out.println(t.getName()+":"+i);
            synchronized (integers){
                //保证一次只有一个线程进来
                integers.add(i);
            }
        }
    }
}

public class S10 {

    public static void main(String[] args) throws InterruptedException {
        List<Integer> nums = new ArrayList<>();
        Thread t1 = new Thread(new NumberWorker(nums,1));
        Thread t2 = new Thread(new NumberWorker(nums,101));
        Thread t3 = new Thread(new NumberWorker(nums,201));
        t1.start();
        t2.start();
        t3.start();
        t1.join();
        t2.join();
        t3.join();
        System.out.println("程序完成");
        System.out.println("总数:"+nums.size());
        System.out.println(nums);
        Collections.sort(nums);
        System.out.println(nums);
    }
}
